import { ref, onMounted, onUnmounted } from "vue";

export function useScreenSafeArea() {
  const top = ref(0);
  const right = ref(0);
  const bottom = ref(0);
  const left = ref(0);

  function updateSafeArea() {
    if (typeof window !== "undefined") {
      // 获取 CSS 环境变量
      const style = getComputedStyle(document.documentElement);

      // 尝试从 CSS 环境变量获取安全区域
      const envTop = style.getPropertyValue("env(safe-area-inset-top)");
      const envRight = style.getPropertyValue("env(safe-area-inset-right)");
      const envBottom = style.getPropertyValue("env(safe-area-inset-bottom)");
      const envLeft = style.getPropertyValue("env(safe-area-inset-left)");

      // 转换像素值
      top.value = parseFloat(envTop) || 0;
      right.value = parseFloat(envRight) || 0;
      bottom.value = parseFloat(envBottom) || 0;
      left.value = parseFloat(envLeft) || 0;

      // 如果 CSS 环境变量不可用，尝试其他方法获取真实安全区域
      if (top.value === 0 && right.value === 0 && bottom.value === 0 && left.value === 0) {
        detectSafeAreaFallback();
      }
    }
  }

  function detectSafeAreaFallback() {
    const userAgent = navigator.userAgent;
    const isIOS = /iPhone|iPad|iPod/i.test(userAgent);
    const isAndroid = /Android/i.test(userAgent);
    const isMobile = isIOS || isAndroid;

    if (!isMobile) return;

    const nativeSafeArea = localStorage.getItem("nativeSafeArea");
    if (nativeSafeArea) {
      const nativeSafeAreaObj = JSON.parse(nativeSafeArea);
      top.value = nativeSafeAreaObj.top;
      right.value = nativeSafeAreaObj.right;
      bottom.value = nativeSafeAreaObj.bottom;
      left.value = nativeSafeAreaObj.left;
      return;
    }


    // 获取视口信息
    const viewport = window.visualViewport || {
      height: window.innerHeight,
      width: window.innerWidth,
      offsetTop: 0,
      offsetLeft: 0,
    };

    // 获取屏幕信息
    const screenHeight = window.screen.height;
    const screenWidth = window.screen.width;
    const isPortrait = screenHeight > screenWidth;

    if (isIOS) {
      // iOS 设备的安全区域处理
      if (isPortrait) {
        // 检查是否为刘海屏 iPhone
        const isNotch = screenHeight >= 812; // iPhone X 及以上
        top.value = isNotch ? 44 : 20; // 状态栏高度
        bottom.value = isNotch ? 34 : 0; // 底部安全区域
      } else {
        // 横屏模式
        top.value = 0;
        bottom.value = 0;
        // 横屏时左右可能有安全区域
        left.value = screenHeight >= 812 ? 44 : 0;
        right.value = screenHeight >= 812 ? 44 : 0;
      }
    } else if (isAndroid) {
      // Android 设备的安全区域处理
      detectAndroidSafeArea(viewport, screenHeight, screenWidth, isPortrait);
    }
  }

  function detectAndroidSafeArea(viewport: any, screenHeight: number, screenWidth: number, isPortrait: boolean) {
    // 计算状态栏高度（更精确的方法）
    const statusBarHeight = getAndroidStatusBarHeight();
    
    // 计算导航栏高度
    const navigationBarHeight = getAndroidNavigationBarHeight(viewport, screenHeight, screenWidth, isPortrait);

    if (isPortrait) {
      top.value = statusBarHeight;
      bottom.value = navigationBarHeight;
    } else {
      // 横屏模式
      top.value = 0;
      bottom.value = 0;
      // 某些 Android 设备横屏时左右有安全区域
      const hasSideSafeArea = screenHeight >= 800; // 大屏设备
      left.value = hasSideSafeArea ? statusBarHeight : 0;
      right.value = hasSideSafeArea ? statusBarHeight : 0;
    }
  }

  function getAndroidStatusBarHeight(): number {
    return 44;
  }

  function getAndroidNavigationBarHeight(viewport: any, screenHeight: number, screenWidth: number, isPortrait: boolean): number {
    // 检查是否有导航栏
    const hasNavigationBar = screenHeight > viewport.height;
    
    if (!hasNavigationBar) {
      return 0;
    }

    // 计算导航栏高度
    const navigationBarHeight = screenHeight - viewport.height;
    
    // 导航栏高度通常在 48-96px 之间
    if (navigationBarHeight > 0 && navigationBarHeight <= 96) {
      return navigationBarHeight;
    }

    // 默认值
    const pixelRatio = window.devicePixelRatio || 1;
    return Math.round(48 * pixelRatio); // 48dp 转换为像素
  }

  onMounted(() => {
    updateSafeArea();
    window.addEventListener("resize", updateSafeArea);
    window.addEventListener("orientationchange", updateSafeArea);
  });

  onUnmounted(() => {
    window.removeEventListener("resize", updateSafeArea);
    window.removeEventListener("orientationchange", updateSafeArea);
  });

  return {
    top,
    right,
    bottom,
    left,
  };
} 